<style scoped>
.cart_list{margin: 10px 12px;}
.cart_row{align-items: stretch;padding: 8px;}
/*.cart_row{background: #fff;margin: 6px auto;width: 350px;border-radius: 13px;}*/
.cart_row>.select{padding: 0 5px;}
.cart_row>.img{width: 100px;height: auto;}
.cart_row>.content{flex-direction: column;align-items: stretch;padding: 1px 4px 1px 8px;}
.cart_row .price{text-align: right;color: #ff9200;font-weight: bold;}
.cart_row .price>.sm{font-size: 0.7em;}
.cart_row .sales{text-align: right;opacity: 0.8;font-size: 0.8em;}

.add_form_param{text-align: right;padding: 4px 8px;}
</style>
<template>
  <div class="outer">
    <form_param :config="form_params">
      <template #_cart_list_="{row}">
        <van-cell-group v-for="(cart,i) in cart_list" inset class="cart_list">
          <cart_row :link_table="this.link_table" :title="cart.title" :head_img="cart.head_img" :price="cart.price" :compute_price="cart.compute_price"
                    v-model:num="cart.num" v-model:sku_id="cart.sku_id" v-model:additional_select="cart.additional_select" @change="change" ></cart_row>

          <p class="add_form_param" v-if="cart_list.length>1 && cart.has_remove_param" @click="add_form_param(cart)"><van-icon name="plus"/>独立设定参数</p>
          <form_param :config="cart.form_params"></form_param>
        </van-cell-group>
      </template>
    </form_param>
  </div>

  <FooterSlot>
    <footer-cart v-bind="cart_menu" @buy="buy"></footer-cart>
  </FooterSlot>
</template>

<script>
import s94 from "s94-js";
import form_param from "@/components/form_param.vue"
import {_get, href_handle} from "@/vue_plugin/router_auto.js";
import {S94Cart} from "@/js/S94Cart.js";
import {S94Model} from "@/js/S94Model.js";
import {ajax, pay_handle} from "@/js/api_tool.js";
import cart_row from "@/components/cart/cart_row.vue";
import FooterSlot from "@/components/slot/FooterSlot.vue";
import FooterCart from "@/components/cart/FooterCart.vue";
import tool from "@/js/tool.js";
import {msg} from "@/js/vant_tool.js";

export default {
  components: {FooterCart, FooterSlot, form_param, cart_row},
  data(){
    //cart_list组件的配置，其中config记录了每一项的参数列表，value记录了每一项的cart对象，has_remove_param记录了每一项是否有隐藏的参数
    let cart_list_config = {name:"_cart_list_", label:"", label_align:'top', type:'_cart_list_', value:[], config:[], has_remove_param:[]};

    return {
      model_name: _get("model_name"),
      action: _get("action", "add"),
      link_table: _get("link_table"),
      this_action: {},
      switch_stock: false,
      list_path: -1, // 模型的列表地址

      cart_list: [],
      form_params_common: [],

      user_address: {},

      cart_list_config: cart_list_config,
      //总的表单参数配置
      form_params: [],

      pay_type: 'yue',
      init_runing: false,
      init_json: '',

      cart_menu: {}
    }
  },
  methods:{
    form_data(){
      //公共参数的值
      let common_value = {}
      this.form_params.forEach(row=>{
        if (row.remove || row.can_edit!=1) return;
        common_value[row.name] = row.value;
      })
      // 分享下单的参数
      let _share_phone_ = s94.cache("_share_phone_");
      if (_share_phone_ && /^1\d{10}$/.test(_share_phone_)) common_value["_share_phone_"] = _share_phone_;

      let keys = ['link_id', "num", "sku_id","additional_select"];
      // 遍历 下单项目
      let res = this.cart_list.map((cart, i)=>{
        let res_row = {}; // cart数据，优先级最低
        Object.keys(cart).forEach((k)=>{
          if (!keys.includes(k)) return;
          let v = cart[k];
          if (k==='link_id'){
            k = this.link_table+'_id';
          }
          res_row[k] = v;
        })
        res_row = Object.assign(res_row, common_value); //公共参数的值，优先级次之
        // 单独设定的值，优先级最高
        let form_params = cart.form_params || [];
        form_params.forEach(row=>{
          if (row.remove || row.can_edit!=1) return;
          res_row[row.name] = row.value;
        })

        return res_row;
      })
      return res;
    },
    change(v){
      setTimeout(()=>{
        this.init();
      }, 20)
    },
    compute_price_handle(form_params_list){
      let cart_menu = {
        all_money: 0,
        vip_money: 0,
        promotion_money: 0,
        promotion_list: [],
        pay_money: 0,
        additional_money: 0,
      }
      Object.values(form_params_list).forEach((form_params, i)=>{
        let compute_price_row = form_params.find((row)=>row.name==='compute_price');
        if (!compute_price_row) {
          msg(`缺少compute_price参数`);
          return href_handle(-1, 1500);
        }
        let compute_price = compute_price_row.value;
        if (typeof compute_price === 'string') compute_price = JSON.parse(compute_price);

        cart_menu.all_money += compute_price.all_money;
        cart_menu.vip_money += compute_price.vip_money;
        cart_menu.promotion_money += compute_price.promotion_money;
        cart_menu.pay_money += compute_price.pay_money;
        cart_menu.additional_money += compute_price.additional_money;

        //更新cart_row
        let cart_row = this.cart_list[i];
        if(cart_row){
          cart_row.compute_price = compute_price;
        }
      })
      this.cart_menu = cart_menu;
    },
    init(){
      if (this.init_runing) return;
      this.init_runing = true;

      let url = `/home/${this.model_name}/batch_add?action=${this.action}&_is_init_=1`;
      let form_data = this.form_data();
      let data_json = JSON.stringify(form_data);
      if (data_json == this.init_json) return;
      this.init_json = data_json;
      ajax({url: url, data: {item: form_data}, method:"post"}, res=>{
        this.init_runing = false;
        this.form_params_handle(res.data, form_data);
        this.compute_price_handle(res.data);
      })
    },
    form_params_handle(form_params_list, form_data){
      let init_need_param = this.this_action.init_need_param ? this.this_action.init_need_param.split(",") : [];
      let cart_name_list = [this.link_table+'_id', "num", "sku_id",'additional_select',"title","head_img","pay_money"]; // 归类到cart_list组件的参数名
      let all_form_map = {}; //
      let form_keys_list = []; //每一项包含的表单标识集，用来计算交集，用于判定指定标识是否存在于该项，不需要去重
      let common_form_keys = [];

      // 计算每个参数配置的key，并根据key汇总
      form_params_list.forEach((form_params, i)=>{
        let cart_row = this.cart_list[i];
        let form_data_row = form_data[i] || {};
        let cart_row_form_params = [];

        let last_common_form_keys = common_form_keys;
        common_form_keys = [];
        form_params.forEach(row=>{
          if (row.name in form_data_row) row.value = form_data_row[row.name];
          let form_key = "_cart_list_";
          // 归类到cart_list组件的参数
          if (cart_name_list.includes(row.name)){
            cart_row[row.name] = row.value;
          }else {
            form_key = row.name + s94.encode(row);
            cart_row_form_params.push(row);
          }
          row.form_key = form_key;
          if (init_need_param.includes(row.name)){
            row.onchange = this.change;
          }
          all_form_map[form_key] = row;

          //和上一轮得出的 common_form_keys 判断新一轮的 common_form_keys
          if (i<=0 || last_common_form_keys.includes(form_key)){
            if (!common_form_keys.includes(form_key)) common_form_keys.push(form_key);
          }
        })
        cart_row.form_params = cart_row_form_params;
      })

      // 计算公共的参数列表
      let common_form_params = [];
      common_form_keys.forEach(form_key=>{
        if (form_key == "_cart_list_"){
          common_form_params.push({name:"_cart_list_", label:"购买项目列表", label_align:'top', type:'_cart_list_'});
        }else {
          common_form_params.push(Object.assign({},all_form_map[form_key]));
        }
      })
      this.form_params = common_form_params;

      // 判定每一项的参数列表中，哪些需要忽略
      this.cart_list.forEach((cart, i)=>{
        cart.has_remove_param = false;
        cart.form_params.forEach(row=>{
          // 在公共参数列表中的参数默认需要忽略
          row.remove = !!~common_form_keys.indexOf(row.form_key);
          if (row.remove && row.can_edit==1 && row.type!='hidden') cart.has_remove_param = true;
        })
      })
    },
    add_form_param(cart, cart_list_config, i){
      let form_params = cart.form_params;
      let options = [];
      form_params.forEach(row=>{
        if (row.remove && row.can_edit==1 && row.type!='hidden'){
          options.push({content:row.label, value:row.name});
        }
      })
      if (!options.length) return;
      tool.select_option(options, '', '选择独立参数').then((value)=>{
        let show_name = value;
        if (!show_name) return;
        let has_remove_param = false;
        form_params.forEach(row=>{
          if (row.name == show_name) row.remove = false;
          if (row.remove && row.can_edit==1 && row.type!='hidden') has_remove_param = true;
        })
        cart_list_config.has_remove_param[i] = has_remove_param;
      })
    },
    buy(){
      // 下单
      let pay_model = S94Model.find(this.model_name);
      let url = `/home/${this.model_name}/batch_add?action=${this.action}`;
      ajax({url: url, data: {item: this.form_data()}, loading:1, method:"post"}, ({data})=>{
        let pay_action = pay_model.findActionHome('','pay');
        if (!pay_action || pay_action.form_param_ids) {
          // 没有找到支付操作，或者支付操作有参数，就跳转到对应列表页处理
          return href_handle(this.list_path);
        }
        let url = `/home/${this.model_name}/batch_pay?action=${pay_action.action}`;
        pay_handle(url, {ids: data.join(',')}, ()=>{
          setTimeout(()=>{ href_handle(this.list_path) }, 1000);
        }, ()=>{
          setTimeout(()=>{ href_handle(this.list_path) }, 1000);
        })
        // 下单成功后，需要移除缓存的下单参数
      })
    },
  },
  computed:{},
  mounted(){
    let app = this;
    let pay_model = S94Model.find(this.model_name);
    if (!pay_model || !pay_model.switch_pay) {
      msg(`参数错误：model_name=${this.model_name}`);
      return href_handle(-1, 1500);
    }
    if (!pay_model.action_map[this.action]) {
      msg(`参数错误：action=${this.action}`);
      return href_handle(-1, 1500);
    }
    this.this_action = pay_model.action_map[this.action];
    // 计算列表地址
    let list_action = pay_model.findActionHome('','list');
    if (list_action) {
      this.list_path = `/model_base/list?model_name=${this.model_name}&action=${list_action.action}`;
    }

    let price_model = S94Model.find(this.link_table);
    if (!price_model || !price_model.switch_price) {
      msg(`参数错误：link_table=${this.link_table}`);
      return href_handle(-1, 1500);
    }
    this.switch_stock = !!price_model.switch_stock;
    this.switch_price_sku = !!price_model.switch_price_sku;
    this.switch_price_additional = !!price_model.switch_price_additional;

    // 结算用的下单参数通过缓存传递，每项需要包含：_cart_id_, goods_id, num, sku_id, title, head_img, price, sku_config[, price_vip][, stock][, promotion_id]等额外参数
    let s94_cart = (new S94Cart(this.model_name, this.action, this.link_table)).get_cache();
    if (!s94_cart.cart_items.length) {
      msg(`缺少购买项目`);
      return href_handle(-1, 1500);
    }
    let cart_list = s94_cart.cart_items.map(row=>{
      row.form_params = [];
      row.has_remove_param = false;
      return row;
    })
    console.log(cart_list);
    this.cart_list = cart_list;
    this.cart_list_config.value = s94_cart.cart_items;

    this.init();

  }
}
</script>